package com.design.twords.activity;

import android.app.ActivityOptions;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.design.twords.MainActivity;
import com.design.twords.R;
import com.design.twords.adatper.MeanChoiceAdapter;
import com.design.twords.config.ConfigData;
import com.design.twords.config.ConstantValue;
import com.design.twords.controller.WordController;
import com.design.twords.database.OcrWordsList;
import com.design.twords.database.Sentence_learn;
import com.design.twords.database.Translation_learn;
import com.design.twords.database.UserConfig;
import com.design.twords.database.Word_all;
import com.design.twords.database.Word_learn;
import com.design.twords.entity.ItemWordMeanChoice;
import com.design.twords.utils.MediaHelper;
import com.design.twords.utils.MyApplication;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Create by Alen
 * Time:  20:17
 */
public class LearnWordActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "LearnWordActivity";

    private TextView newword_1, newword_2, reviewword_1, reviewword_2, time, wordname, phone, tips;
    private ImageView back, remark, delete, wordplay, addword;
    private Button mohu, renshi, burenshi;

    private RecyclerView recyclerView;
    private LinearLayout wordcard_btgroup, wordcard_bottomgroup;
    private CardView cardTip;

    //private WordController wordController;
    private MeanChoiceAdapter meanChoiceAdapter;

    private RemarkDialog remarkDialog;
    private ProgressDialog progressDialog;

    private List<ItemWordMeanChoice> wordMeanChoices = new ArrayList<>();


    private static final int UPDATE_TIME = 0;
    private static final int PREPARE_DATA = 1;
    private static final int FINISH_DATA = 2;


    public static boolean needUpdate = true;

    public int newWordNumb = 0;
    public int reviewWordNumb = 0;

    private int currentMode;

    private String tipSentence;
    private int daywords;
    private String booktype;
    private String saveRemark;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDATE_TIME:
                    time.setText(String.valueOf(msg.arg1+1));
                    break;
                case PREPARE_DATA:
                    showProgressDialog("正在为您生成单词");
                    break;
                case FINISH_DATA:
                    showProgressDialog("成功生成单词");
                    progressDialog.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wordcard);
        //添加到Activity 列表中
        MyApplication.getInstance().addActivity(this);
        initDeatil();
        initView();
        initListener();
        initData();


        meanChoiceAdapter = new MeanChoiceAdapter(wordMeanChoices, this, R.layout.item_meanchoice);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(meanChoiceAdapter);
        meanChoiceAdapter.setListener(new MeanChoiceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, ItemWordMeanChoice meanChoice) {
                if(MeanChoiceAdapter.isFirstClick){
                    Log.d(TAG, "选择了：" + meanChoice.getId());
                    Log.d(TAG, "目标是： " + WordController.currentWordId);
                    //选错了
                    if (meanChoice.getId() != WordController.currentWordId){
                        switch (WordController.currentMode) {
                            case WordController.REVIEW_AT_TIME:
                                WordController.reviewNewWordDone(WordController.currentWordId, false);
                                break;
                            case WordController.REVIEW_GENERAL:
                                WordController.reviewWordDone(WordController.currentWordId, false);
                                break;
                        }
                        MeanChoiceAdapter.isFirstClick = false;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent();
                                intent.setClass(LearnWordActivity.this, WordDetailActivity.class);
                                intent.putExtra("wordId", WordController.currentWordId+"");
                                intent.putExtra("booktype", booktype);
                                intent.putExtra("flags", ConstantValue.LEARN_WORD);
                                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LearnWordActivity.this).toBundle());
                                MeanChoiceAdapter.isFirstClick = true;
                            }
                        }, 500);
                    }else {
                        switch (WordController.currentMode) {
                            case WordController.REVIEW_AT_TIME:
                                WordController.reviewNewWordDone(WordController.currentWordId, true);
                                break;
                            case WordController.REVIEW_GENERAL:
                                WordController.reviewWordDone(WordController.currentWordId, true);
                                break;
                        }
                        reviewWordNumb++;
                        reviewword_1.setText(reviewWordNumb + "");
                        MeanChoiceAdapter.isFirstClick = false;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                updateStatus();
                                MeanChoiceAdapter.isFirstClick = true;
                            }
                        }, 500);
                    }
                }
            }
        });

    }
    private void initDeatil(){
        List<UserConfig> all = LitePal.where("userId = ?", ConfigData.getUserId()).find(UserConfig.class);
        int bookid = all.get(0).getCurrentBookId();
        booktype = ConstantValue.getTypeById(bookid);
        daywords = all.get(0).getDaywords();

        //初始化新词列表
        WordController.setLearnWordsList(all.get(0).getLastStartTime());
        //初始化复习单词列表
        WordController.setReviewWordsList();


    }
    private void showProgressDialog(String content) {
        progressDialog = new ProgressDialog(LearnWordActivity.this);
        progressDialog.setTitle("请稍后");
        progressDialog.setMessage(content);
        progressDialog.setCancelable(true);
        progressDialog.show();
    }


    @Override
    protected void onStart() {
        super.onStart();

        if(needUpdate){
            updateStatus();
            needUpdate = false;
        }

    }



    private void initData() {
        if (daywords != 0 ){
            newword_2.setText("/" + daywords);
            reviewword_2.setText("/" + (WordController.needReviewWord.size() + WordController.justLearnedWord.size()));
        }else {
            Toast.makeText(this,"出了点小问题", Toast.LENGTH_LONG).show();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(1000*60);
                        Message msg = new Message();
                        msg.what = UPDATE_TIME;
                        msg.arg1 = Integer.valueOf(time.getText().toString());
                        handler.sendMessage(msg);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }


    private void initView() {
        newword_1 = findViewById(R.id.wordcard_newwords_1);
        reviewword_1 = findViewById(R.id.wordcard_reviewwords_1);
        newword_2 = findViewById(R.id.wordcard_newwords_2);
        reviewword_2 = findViewById(R.id.wordcard_reviewwords_2);
        time = findViewById(R.id.wordcard_studytime);
        wordname = findViewById(R.id.wordcard_wordname);
        phone = findViewById(R.id.wordcard_phone);
        tips = findViewById(R.id.wordcard_sentence);

        mohu = findViewById(R.id.wordcard_vague);
        renshi = findViewById(R.id.wordcard_know);
        burenshi = findViewById(R.id.wordcard_unknown);

        back = findViewById(R.id.wordcard_back);
        remark = findViewById(R.id.wordcard_remark);
        delete = findViewById(R.id.wordcard_delete);
        wordplay = findViewById(R.id.wordcard_wordplay);
        addword = findViewById(R.id.wordcard_add);

        cardTip = findViewById(R.id.wordcard_tipscard);
        wordcard_btgroup = findViewById(R.id.wordcard_btgroup);
        wordcard_bottomgroup = findViewById(R.id.wordcard_bottomgroup);
        recyclerView = findViewById(R.id.wordcard_recycleview);


    }

    private void initListener() {
        mohu.setOnClickListener(this);
        renshi.setOnClickListener(this);
        burenshi.setOnClickListener(this);

        back.setOnClickListener(this);
        remark.setOnClickListener(this);
        delete.setOnClickListener(this);
        wordname.setOnClickListener(this);
        wordplay.setOnClickListener(this);
        addword.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        Intent intent = new Intent();
        intent.setClass(LearnWordActivity.this, WordDetailActivity.class);
        intent.putExtra("wordId", WordController.currentWordId+"");
        intent.putExtra("booktype", booktype);
        intent.putExtra("flags", ConstantValue.LEARN_WORD);

        switch (v.getId()){
            //认识
            case R.id.wordcard_know:
                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LearnWordActivity.this).toBundle());
                WordController.learnNewWordDone(WordController.currentWordId, true);
                newWordNumb++;
                newword_1.setText(newWordNumb + "");
                break;
            case R.id.wordcard_unknown:
                //跳转到单词详情界面
                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LearnWordActivity.this).toBundle());
                WordController.learnNewWordDone(WordController.currentWordId, false);
                break;
            case R.id.wordcard_vague:
                if (!TextUtils.isEmpty(tipSentence.trim())) {
                    tips.setText(tipSentence);
                    cardTip.setVisibility(View.VISIBLE);
                    MediaHelper.play(tipSentence);
                } else {
                    Toast.makeText(this, "暂无提示", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.wordcard_delete:
                WordController.removeOneWord(WordController.currentWordId);
                updateStatus();
                break;
            case R.id.wordcard_wordname:
            case R.id.wordcard_wordplay:
                MediaHelper.play(wordname.getText().toString());
                break;
            case R.id.wordcard_back:
                onBackPressed();
                finish();
                break;
            case R.id.wordcard_remark:
                remarkDialog = new RemarkDialog (LearnWordActivity.this);
                remarkDialog.showNow(getSupportFragmentManager(), "RemarkDialog");
                remarkDialog.remark.setText(saveRemark);
                remarkDialog.bt_save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String s = remarkDialog.remark.getText().toString();
                        saveRemark(WordController.currentWordId, booktype, s);
                        remarkDialog.dismiss();
                    }
                });
                break;
            case R.id.wordcard_add:
                //先查询是否有该单词
                if(LitePal.where("word = ?",wordname.getText().toString()).find(OcrWordsList.class).isEmpty()){
                    OcrWordsList ocr = new OcrWordsList();
                    ocr.setWordId(WordController.currentWordId);
                    ocr.setWord(wordname.getText().toString());
                    ocr.setWordBook(WordController.wordBook);
                    ocr.save();
                    Toast.makeText(LearnWordActivity.this,"添加成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(LearnWordActivity.this,"表中已有该单词",Toast.LENGTH_SHORT).show();
                }

                addword.setVisibility(View.GONE);
                break;
        }

    }


    private void updateStatus() {
        tipSentence = "";
        cardTip.setVisibility(View.GONE);
        addword.setVisibility(View.VISIBLE);

        //随机选择背诵状态
        WordController.currentMode = WordController.whatToDo();
        switch (WordController.currentMode){
            case WordController.REVIEW_AT_TIME:
                Log.i(TAG, "正在复习新单词");
                WordController.currentWordId = WordController.reviewNewWord();
                showReview();
                break;
            case WordController.REVIEW_GENERAL:
                Log.i(TAG, "正在复习旧单词");
                WordController.currentWordId = WordController.reviewWord();
                showReview();
                break;
            case WordController.NEW_LEARN:
                Log.i(TAG, "正在学习新单词");
                WordController.currentWordId = WordController.learnNewWord();
                showLearn();
                break;
            case WordController.TODAY_MASK_DONE:
                Toast.makeText(this, "已完成今日任务", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, FinishActivity.class);
                intent.putExtra("wordnumb", daywords);
                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LearnWordActivity.this).toBundle());
                finish();
                break;
        }

        Log.i(TAG, "currentId " + WordController.currentWordId);
        List<Word_learn> words = LitePal.where("wordId = ?", WordController.currentWordId + "").select("wordId", "word", "ukPhone", "usPhone").find(Word_learn.class);
        if(!words.isEmpty()){
            Word_learn word = words.get(0);
            wordname.setText(word.getWord());

            saveRemark = word.getRemark();

            if(word.getUsPhone() != null){
                phone.setText(word.getUsPhone());
            }else {
                phone.setText(word.getUkPhone());
            }

            //显示单词立刻播放读音
            if (WordController.currentMode != WordController.TODAY_MASK_DONE)
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        MediaHelper.play(wordname.getText().toString());
                    }
                }).start();

            //获取翻译信息
            List<Translation_learn> transList = LitePal.where("wordId = ?", word.getWordId() + "").find(Translation_learn.class);
            StringBuilder builder = new StringBuilder();
            if (!transList.isEmpty()){
                builder.append(transList.get(0).getWordType() + ". " + transList.get(0).getCHSMeaning());
            }

            List<Sentence_learn> sentsList = LitePal.where("wordId = ?", word.getWordId() + "").find(Sentence_learn.class);
            if (!sentsList.isEmpty())
                tipSentence = sentsList.get(0).getSentence();


            if(WordController.currentMode == WordController.REVIEW_AT_TIME || WordController.currentMode ==WordController.REVIEW_GENERAL){
                wordMeanChoices.clear();

                List<Translation_learn> wrongTransList = LitePal.where("wordId != ?", word.getWordId() + "").limit(3).find(Translation_learn.class);
                //随机排列
                Collections.shuffle(wrongTransList);

                //如果选项视图可见
                if (recyclerView.getVisibility() == View.VISIBLE){
                    //添加正确意思
                    wordMeanChoices.add(new ItemWordMeanChoice(WordController.currentWordId, builder.toString(), ItemWordMeanChoice.RIGHT));
                    //添加三个错误意思
                    for (int i = 0; i < 3; i++) {
                        wordMeanChoices.add(new ItemWordMeanChoice(-1, wrongTransList.get(i).getWordType() + ". " + wrongTransList.get(i).getCHSMeaning(), ItemWordMeanChoice.WRONG));
                    }
                    // 打乱顺序
                    Collections.shuffle(wordMeanChoices);
                    meanChoiceAdapter.notifyDataSetChanged();

                }
            }

        }else {
            Toast.makeText(this, "发生错误，请重试", Toast.LENGTH_SHORT).show();
            onBackPressed();

        }


    }

    private void showLearn() {
        recyclerView.setVisibility(View.GONE);
        wordcard_bottomgroup.setVisibility(View.VISIBLE);
        wordcard_btgroup.setVisibility(View.VISIBLE);
    }

    private void showReview() {
        recyclerView.setVisibility(View.VISIBLE);
        wordcard_bottomgroup.setVisibility(View.VISIBLE);
        wordcard_btgroup.setVisibility(View.GONE);
    }

    public void saveRemark(long wordId, String wordtype, String remark){
        List<Word_all> word_alls = LitePal.where("wordId = ? and wordBook = ?", wordId + "", wordtype).find(Word_all.class);
        Word_all word_all = word_alls.get(0);
        word_all.setRemark(remark);
        word_all.save();

        List<Word_learn> word_learns = LitePal.where("wordId = ? and wordBook = ?", wordId + "", wordtype).find(Word_learn.class);
        Word_learn word_learn = word_learns.get(0);
        word_learn.setRemark(remark);
        word_learn.save();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(LearnWordActivity.this, MainActivity.class);
        startActivity(intent);
        MediaHelper.releasePlayer();
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        needUpdate = true;
        MyApplication.getInstance().removeActivity(this);
    }


    public static class RemarkDialog extends DialogFragment{

        private EditText remark;
        private TextView wordnumb;
        private Button bt_save;
        private LayoutInflater myInflater;
        private View itemview;

        public RemarkDialog(Context context) {
            this.myInflater = LayoutInflater.from(context);
            itemview = myInflater.inflate(R.layout.dialog_wordremark, null);

            remark = itemview.findViewById(R.id.wordremark_et);
            wordnumb = itemview.findViewById(R.id.wordremark_size);
            bt_save = itemview.findViewById(R.id.wordremark_bt);

        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
            return itemview;
        }

        @Override
        public void onStart() {
            super.onStart();
            remark.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});
            remark.addTextChangedListener(new TextWatcher() {
                private CharSequence temp;

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    temp = s;
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    wordnumb.setText(temp.length()+"");
                }
            });
        }

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        }

        /**
         * Dismiss the fragment and its dialog.  If the fragment was added to the
         * back stack, all back stack state up to and including this entry will
         * be popped.  Otherwise, a new transaction will be committed to remove
         * the fragment.
         */
        @Override
        public void dismiss() {
            super.dismiss();

        }
    }



}
